package com.witmed.lib_http.interceptor


import com.blankj.utilcode.util.EncryptUtils
import okhttp3.Interceptor
import okhttp3.MediaType
import okhttp3.RequestBody
import okhttp3.Response
import okio.Buffer
import org.json.JSONObject
import java.util.Arrays


class SignInterceptor:Interceptor {
    //通过拦截器自动在请求中添加md5的sign签名
    override fun intercept(chain: Interceptor.Chain): Response {
        val request = chain.request()
        val builder = request.newBuilder()

        builder.url(request.url())
        builder.headers(request.headers())

        val body = request.body()
        val buffer = Buffer()
        body?.writeTo(buffer)
        var json = buffer.toString()

        json=json.substring(json.indexOf("{"),json.lastIndexOf("}")+1)

        val jsonObject = JSONObject(json)
        val keys = jsonObject.keys()
        val sb = StringBuffer()
        while (keys.hasNext()){
            val key = keys.next()
            sb.append(jsonObject.get(key))
        }
        val sign = createSign(sb.toString())
        jsonObject.put("sign",sign)
        val requestBody = RequestBody.create(
            MediaType.parse("application/json;charset=UTF-8"),
            jsonObject.toString()
        )
        builder.post(requestBody)
        return chain.proceed(builder.build())
    }

    private fun createSign(json:String):String {
        val array = json.toCharArray()
        Arrays.sort(array)
        val string = String(array)
        return EncryptUtils.encryptMD5ToString(string+"tamboo").toLowerCase()
    }


}